package com.cw.jeeyt.service.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cw.jeeyt.service.intf.system.InitializeDataService;

/**
 * 初始化框架数据库
 *
 * @author chenw
 */
@WebListener
public class FrameDbInitListener implements ServletContextListener {

    private Logger logger = LoggerFactory.getLogger(FrameDbInitListener.class);
    @Autowired
    private InitializeDataService initializeDataService;

    @Override
    public void contextDestroyed(ServletContextEvent servletCtxEvent) {
    }

    /**
     * 框架数据库表初始化
     *
     * @param servletCtxEvent
     * @see
     */
    @Override
    public void contextInitialized(ServletContextEvent servletCtxEvent) {
        WebApplicationContextUtils.getRequiredWebApplicationContext(servletCtxEvent.getServletContext())
            .getAutowireCapableBeanFactory()
            .autowireBean(this);
        logger.info("---init base data...");
        try {
            initBasicData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("---init base data finished--。");

    }

    /**
     * 更新系统运行需要的基础数据
     */
    private void initBasicData() throws Exception {
        initializeDataService.initData();
    }
}
